package com.taihe.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taihe.domain.User;
import com.taihe.redis.Redis;
import com.taihe.service.UserService;
import com.taihe.util.FactoryTest;
import com.taihe.util.RedisUtil;
import com.taihe.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

import static javafx.scene.input.KeyCode.F;

/**
 * Created by zwt on 2018/7/20.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private Redis redis;

    @RequestMapping("list")
    @ResponseBody
    public PageInfo<User> list(){
        PageHelper.startPage(0,1);
        //UserService userService = SpringUtil.getBean(UserService.class);
        UserService userService = FactoryTest.instance(1);
        List<User> users = userService.selectAll();
        PageInfo<User> pageInfo = new PageInfo<User>(users);
        return pageInfo;
    }

    @RequestMapping("add")
    @ResponseBody
    public int add(){
        User user = new User();
        user.setName("11111111111");
        UserService userService = SpringUtil.getBean(UserService.class);
        int i  = 0;
        try {
            i = userService.save(user);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return i;
    }

    @RequestMapping("getUserInfo")
    @ResponseBody
    public User getUserInfo(@RequestParam Long id){
        UserService userService = SpringUtil.getBean(UserService.class);
        String key = "USER_"+String.valueOf(id);
        User user = redis.get(key, User.class);
        String s = JSON.toJSONString(user);
        if(null == user){
            user = userService.selectOne(id);
            redis.set(key,user);
        }
        return user;
    }



}
